package com.yizhu.zczy.address.service.impl;

import com.yizhu.zczy.common.utils.PageUtils;
import com.yizhu.zczy.common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.yizhu.zczy.address.dao.RegionDao;
import com.yizhu.zczy.address.entity.RegionEntity;
import com.yizhu.zczy.address.service.RegionService;


@Service
public class RegionServiceImpl extends ServiceImpl<RegionDao, RegionEntity> implements RegionService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RegionEntity> page = this.page(
                new Query<RegionEntity>().getPage(params),
                new QueryWrapper<RegionEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据父查询子
     * @param pid
     * @return
     */
    @Override
    public List<RegionEntity> queryByParentId(Integer pid) {
        QueryWrapper<RegionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",pid);
        List<RegionEntity> list = baseMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 获取所有城市，封装子城市
     * @return
     */
    @Override
    public List<RegionEntity> getAllCity() {
        List<RegionEntity> list = this.list();
        //封装
        return  this.encapsulation(list, 0);
    }

    private List<RegionEntity> encapsulation(List<RegionEntity> list, Integer parentId) {
        List<RegionEntity> regionEntityList = list.stream().filter(regionEntity -> regionEntity.getPid() == parentId).map(regionEntity -> {
            regionEntity.setChildren(encapsulation(list, regionEntity.getId()));
            return regionEntity;
        }).collect(Collectors.toList());
        return regionEntityList;
    }

}